﻿using Infrastructure.Config.Core.External;
using Infrastructure.ExternalService.Core.Extensions;
using Infrastructure.ExternalService.Core.Requests;
using Infrastructure.ExternalService.Core.Responses;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Net.Http;
using System.Threading.Tasks;
using Edu.Http.Extensions;
using Edu.Http.Proxy;

namespace Infrastructure.ExternalService.Core.Imp.Extensions
{
    public class ExtensionSystemClient : BaseHttpClient, IExtensionSystemClient
    {
        private readonly OrderCenterApiOptions _orderingOptions;
        private readonly string formUrlencoded = "application/x-www-form-urlencoded";

        public ExtensionSystemClient(IOptions<OrderCenterApiOptions> options,
        HttpClient client, ILoggerFactory loggerFactory)
        : base(client, loggerFactory, options.Value.ExtensionSystemOptions.EndPoint)
        {
            _orderingOptions = options.Value ?? throw new HttpProxyException($"{nameof(ExtensionSystemClient)}配置获取失败");
            loggerFactory.CreateLogger<ExtensionSystemClient>();
        }


        /// <summary>
        /// 通过地区编码获取门店
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="HttpProxyException"></exception>

        public async Task<SchoolInfo> GetSchoolByAreaAsync(GetSchoolByAreaRequest request)
        {
            var formStr = ConvertRequestToCommonFormUrlEncode(request);
            var response = await PostJsonAsync<WrapResponse<SchoolResponse>>(url: _orderingOptions.ExtensionSystemOptions.GetSchoolByArea, jsonStr: formStr, formUrlencoded, headers: null);
            if (response != null && response.Success && response.Data != null)
            {
                return response.Data?.Data[0];
            }

            throw new HttpProxyException($"{response.Msg}");
        }

    }
}
